#!/usr/bin/env node

/**
 * 开发启动脚本 - 确保干净的开发环境
 * 解决 Mac 上性能问题和进程残留问题
 */

const { spawn, exec } = require('child_process');
const { cleanup } = require('./cleanup');
const path = require('path');
const os = require('os');

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m'
};

function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

function checkNodeVersion() {
  const nodeVersion = process.version;
  const majorVersion = parseInt(nodeVersion.slice(1).split('.')[0]);
  
  if (majorVersion < 16) {
    log('警告: 建议使用 Node.js 16 或更高版本以获得最佳性能', 'yellow');
  }
}

function optimizeForMac() {
  if (os.platform() === 'darwin') {
    // macOS 特定优化
    process.env.ELECTRON_ENABLE_LOGGING = '1';
    process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = '1';
    
    // 启用垃圾回收
    if (!process.execArgv.includes('--expose-gc')) {
      log('启用垃圾回收优化...', 'cyan');
    }
  }
}

function waitForPort(port, timeout = 30000) {
  return new Promise((resolve, reject) => {
    const startTime = Date.now();
    
    function check() {
      exec(`lsof -ti:${port}`, (error, stdout) => {
        if (stdout.trim()) {
          resolve();
        } else if (Date.now() - startTime > timeout) {
          reject(new Error(`端口 ${port} 在 ${timeout}ms 内未启动`));
        } else {
          setTimeout(check, 1000);
        }
      });
    }
    
    check();
  });
}

async function startDevelopment() {
  try {
    log('🚀 启动开发环境...', 'bright');
    
    // 检查 Node.js 版本
    checkNodeVersion();
    
    // macOS 优化
    optimizeForMac();
    
    // 清理环境
    log('🧹 清理开发环境...', 'yellow');
    await cleanup();
    
    // 等待一秒确保清理完成
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    log('✅ 环境清理完成', 'green');
    
    // 启动 Vite 开发服务器
    log('📦 启动 Vite 开发服务器...', 'blue');
    const viteProcess = spawn('npm', ['run', 'dev'], {
      stdio: 'pipe',
      cwd: path.join(__dirname, '..')
    });
    
    viteProcess.stdout.on('data', (data) => {
      const output = data.toString();
      if (output.includes('Local:') || output.includes('ready')) {
        log('✅ Vite 服务器已启动', 'green');
      }
      process.stdout.write(`[Vite] ${output}`);
    });
    
    viteProcess.stderr.on('data', (data) => {
      process.stderr.write(`[Vite Error] ${data}`);
    });
    
    // 等待 Vite 启动
    log('⏳ 等待 Vite 服务器启动...', 'cyan');
    await waitForPort(8080);
    
    // 启动 Electron
    log('⚡ 启动 Electron 应用...', 'magenta');
    const electronProcess = spawn('npx', ['cross-env', 'NODE_ENV=development', 'electron', '.'], {
      stdio: 'pipe',
      cwd: path.join(__dirname, '..')
    });
    
    electronProcess.stdout.on('data', (data) => {
      process.stdout.write(`[Electron] ${data}`);
    });
    
    electronProcess.stderr.on('data', (data) => {
      process.stderr.write(`[Electron Error] ${data}`);
    });
    
    // 处理进程退出
    function cleanup() {
      log('🛑 正在关闭开发服务器...', 'yellow');
      
      if (viteProcess && !viteProcess.killed) {
        viteProcess.kill('SIGTERM');
      }
      
      if (electronProcess && !electronProcess.killed) {
        electronProcess.kill('SIGTERM');
      }
      
      setTimeout(() => {
        process.exit(0);
      }, 2000);
    }
    
    process.on('SIGINT', cleanup);
    process.on('SIGTERM', cleanup);
    
    electronProcess.on('exit', (code) => {
      log(`Electron 进程退出，代码: ${code}`, code === 0 ? 'green' : 'red');
      cleanup();
    });
    
    viteProcess.on('exit', (code) => {
      log(`Vite 进程退出，代码: ${code}`, code === 0 ? 'green' : 'red');
      cleanup();
    });
    
    log('🎉 开发环境启动完成！', 'bright');
    
  } catch (error) {
    log(`❌ 启动失败: ${error.message}`, 'red');
    process.exit(1);
  }
}

if (require.main === module) {
  startDevelopment();
}

module.exports = { startDevelopment };